<template>
  <div>
    <van-nav-bar title="成员管理" left-arrow @click-left="$router.replace('/family/admin')"/>

    <!-- 成员搜索框 -->
    <van-form>
      <van-search shape="round" show-action placeholder="请输入家族人员姓名"
                  v-model="memberName" @input="searchPeople"
                  @cancel="showPopup = false; memberName = ''; searchList = []"/>
    </van-form>

    <!-- 成员搜索结果列表 -->
    <van-cell is-link center v-for="people in searchList" :key="people.id"
              @click="clickedPeople = people; showSheet = true">
      <template #title>
        <van-image round width="52" height="52" :src="people.portrait || defaultPortrait(people.gender)"/>
        <p>
          <span>{{ people.name }}</span>
          <sex-tag :sex="people.gender"/>
        </p>
      </template>
      <template #default>
        <van-tag color="#6c757d" v-if="people.deathDate">已逝</van-tag>
        <van-tag color="#28a745" v-else>健在</van-tag>
      </template>
    </van-cell>

    <!-- 人员管理动作面板 -->
    <van-action-sheet v-model="showSheet" cancel-text="取消" :description="clickedPeople.name">
      <van-grid square :border="false">
        <van-grid-item icon="add-o" text="添加亲人"
                       @click="$router.push(`/family/admin/member/add?pid=${clickedPeople.id}`)"/>
        <van-grid-item icon="delete-o" text="移除此人" @click="removeGenealogyPeople"/>
        <van-grid-item icon="edit" text="编辑信息"
                       @click="$router.push(`/family/admin/member/edit?pid=${clickedPeople.id}`)"/>
        <van-grid-item icon="manager-o" :text="`${clickedPeople.gender === 0 ? '他' : '她'}的主页`"
                       @click="$router.push(`/family/member/info/2?pid=${clickedPeople.id}`)"/>
      </van-grid>
    </van-action-sheet>

    <!-- 添加成员按钮 -->
    <div class="add-member-container">
      <van-button type="primary" size="large" round @click="showAddMemberDialog = true">
        <van-icon name="plus" style="margin-right: 8px"/>
        添加成员
      </van-button>
    </div>

    <!-- 添加成员弹窗 -->
    <van-popup v-model="showAddMemberDialog" position="bottom" :close-on-click-overlay="false" :style="{ height: '80%' }">
      <div class="add-member-popup">
        <van-nav-bar title="添加成员" left-text="取消" right-text="保存" 
                     @click-left="showAddMemberDialog = false" @click-right="handleSaveMember"/>
        
        <div class="member-form-container">
          <member-form @save="handleSaveMember" @hidden-form="showAddMemberDialog = false" 
                       :people="newMemberData" :anonymous="true" ref="memberForm"/>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script>
import SexTag from '@/components/tag/sex-tag'
import {defaultPortrait} from "@/mixin/common-utils";
import MemberForm from "@/components/business/member-form";

export default {
  name: "index",
  components: {SexTag, MemberForm},
  mixins: [defaultPortrait],
  data() {
    return {
      memberName: "",
      searchList: [],
      showSheet: false,
      clickedPeople: {},
      // 添加成员相关
      showAddMemberDialog: false,
      newMemberData: {
        id: -1,
        gender: 0,
        generation: 0,
        generationName: undefined,
        residence: undefined,
        birthplace: undefined
      }
    }
  },
  watch: {
    memberName(newVal) {
      // if (newVal.length === 0) {
      //   this.searchList = []
      // }
    }
  },
  mounted() {
    this.searchPeople()
  },
  methods: {
    searchPeople() {
      // if (this.memberName.length === 0) {
      //   return
      // }

      this.$api.genealogy.listMemberByName({name: this.memberName}).then(list => {
        this.searchList = list
      }).catch((msg) => {
        this.$toast({message: msg, position: 'bottom'})
      });
    },
    removeGenealogyPeople() {
      this.showSheet = false
      const genealogyName = this.$store.getters["genealogy/defaultGenealogy"].title

      this.$dialog.confirm({
        title: '移除成员',
        message: `您确定要从《${genealogyName}》家族中移除<p style="color: #ee0a24">${this.clickedPeople.name}</p>这个家族成员吗？`,
      }).then(() => {
        this.$api.genealogy.removePeople({peopleId: this.clickedPeople.id}).then(() => {
          // 更新家族仓库中的家族列表信息
          this.$store.dispatch('genealogy/updateGenealogyStore')
          this.memberName = ''
          this.$toast.success('移除成功')
        }).catch(msg => {
          this.$toast({message: msg, position: 'bottom'})
        })
      }).catch(() => {
      })
    },
    handleSaveMember(formData) {
      // 使用 relativeType = 7 进行独立添加
      this.$api.genealogy.addRelative(formData, {relativeType: 7}).then(() => {
        this.showAddMemberDialog = false
        this.$refs.memberForm.resetForm()
        this.$toast.success('添加成员成功')
        
        // 更新家族仓库中的家族列表信息
        this.$store.dispatch('genealogy/updateGenealogyStore')
        // 刷新成员列表
        this.searchPeople()
      }).catch(msg => {
        this.$toast({message: msg, position: 'bottom'})
      })
    }
  }
}
</script>

<style scoped>
/deep/ .van-cell__title {
  display: flex;
}

.van-cell__title p {
  margin-left: 8px;
}

/* 添加成员按钮容器 */
.add-member-container {
  position: fixed;
  bottom: 20px;
  left: 20px;
  right: 20px;
  z-index: 100;
}

/* 添加成员弹窗样式 */
.add-member-popup {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.member-form-container {
  flex: 1;
  overflow-y: auto;
  padding: 0 16px;
}
</style>
